let express = require('express')
let router = express.Router()

let mysqlHelper = require('../utils/mysqlHelper.js')
let utils = require('../utils/utils')

/* 
* 根据path跳转
* name可以为中英文
* 首页在 config/index.js 中配置 dashboard， 这个path需要包含在menu表中
* 动态路由：数据库中配置
* 静态路由：config/route.js
* 主菜单根节点：path不能为null，component可以为null，name唯一
* 菜单节点    ：path不能为null，component不能为null，name唯一
*/

// 获取主菜单 maoyuan
router.get('/my', async function(req, res, next) {
    let result = {}
    try {
        let data = {}
        let userName = utils.getQueryValue(req.query.userName)
        let sqlWhere = " and b.userId = (select userId from sys_user where userName='"+userName+"')"
        let sqlStr = "select a.id, a.parentId, a.name, a.path, a.component, a.icon, a.title, a.affix,a.keepalive from sys_menu a "
        if (userName!='admin')
            sqlStr += "inner join (   \
                        select distinct id from(  \
                            select '1' as id        \
                            union select '2' as id    \
                            union select distinct r.permissionId as id from sys_role_permission r \
                                inner join sys_user_role b on r.roleId=b.roleId  \
                                where r.permissionId is not null "+ sqlWhere
                    + ")d  \
                      ) b on a.id=b.id "
        sqlStr +=" where a.type='menu' and hidden!=1  order by parentId,orderInList "
        rows = await mysqlHelper.query(sqlStr)
        rows.forEach((menu, index, arr) => {
            menu.meta = {"title":menu.title, "icon":menu.icon, "type":menu.type, affix: menu.affix}
        })
        // 倒序删除子菜单数量=0的主菜单
        let myMenus = rows.filter(row => row.parentId == '0')
        let menusNeedToRemove = []
        myMenus.forEach((menu, index, arr) => {
            menu.children = rows.filter(row => row.parentId == menu.id) 
            if (menu.children.length == 0) {
                menusNeedToRemove.push(index)
            }
        })
        menusNeedToRemove.reverse()
        menusNeedToRemove.forEach((value, index, arr) => {
            myMenus.splice(value, 1)
        })
        data.menu = myMenus

        sqlStr = "select a.alias from sys_menu a "
        if (userName!='admin')
            sqlStr += "inner join (                \
                        select 1 as menuId      \
                        union                   \
                        select distinct r.permissionId as menuId from sys_role_permission r \
                        inner join sys_user_role b on r.roleId = b.roleId \
                        where r.permissionId is not null " + sqlWhere
                    + ") b on a.id=b.menuId "
        sqlStr += " where a.type='button'  \
                    order by parentId,orderInList"
        rows = await mysqlHelper.query(sqlStr)
        let permissions = []
        rows.forEach((menu, index, arr) => {
            permissions.push(menu.alias)
        })
        data.permissions = permissions

        result.code=200
        result.data = data
        result.success = true
    } catch (err) {
        result.code=400
        result.success = false
        result.err = err.message
    }
    res.json(result)
})

// 设置菜单页面，获取菜单列表 maoyuan
router.get('/list', async function(req, res, next) {
    let result = {}
    try {
        let rows = await mysqlHelper.query('select a.*,orderInList sort from sys_menu a order by parentId,orderInList')
        rows.forEach((menu, index, arr)=>{
            menu.meta = {"title":menu.title, "icon":menu.icon, "type":menu.type, "fullpage":menu.fullpage, "hidden":menu.hidden, "hiddenBreadcrumb":menu.hiddenBreadcrumb,"tag":menu.tag, "color":menu.color, affix:menu.affix, keepAlive:menu.keepAlive}
        })
        
        let allMenus = rows.filter(row => row.parentId == '0')
        allMenus.forEach((menu, index, arr) => {
            menu.children = rows.filter(row => row.parentId == menu.id)
            menu.children.forEach((subMenu, i, ar)=>{
                subMenu.children = rows.filter(row => row.parentId == subMenu.id)
            })
        })
        result.code=200
        result.data = allMenus
        result.success = true
    } catch (err) {
        result.code=400
        result.success = false
        result.err = err.message
    }
    res.json(result)
})

// 设置菜单页面，修改添加菜单  maoyuan
router.post('/', async function(req, res, next){
    let result = {}    
    try{
        let id = utils.getQueryValue(req.body.id)
        let title = utils.getQueryValue(req.body.meta.title)===''?null:"'"+req.body.meta.title+"'"
        let name= utils.getQueryValue(req.body.name)===''?null:"'"+req.body.name+"'"
        let icon = utils.getQueryValue(req.body.meta.icon)===''?null:"'"+req.body.meta.icon+"'"
        let type = utils.getQueryValue(req.body.meta.type)===''?null:"'"+req.body.meta.type+"'"
        let hidden = utils.getQueryValue(req.body.meta.hidden)===''?0:req.body.meta.hidden
        let hiddenBreadcrumb = utils.getQueryValue(req.body.meta.hiddenBreadcrumb)===''?0:req.body.meta.hiddenBreadcrumb
        let tag = utils.getQueryValue(req.body.meta.tag)===''?null:"'"+req.body.meta.tag+"'"       
        let color = utils.getQueryValue(req.body.meta.color)===''?null:"'"+req.body.meta.color+"'"       
        let fullpage = utils.getQueryValue(req.body.meta.fullpage)===''?0:req.body.meta.fullpage
        let path = utils.getQueryValue(req.body.path)===''?null:"'"+req.body.path+"'"
        let component = utils.getQueryValue(req.body.component)===''?null:"'"+req.body.component+"'"
        let affix = utils.getQueryValue(req.body.meta.affix)===''?0:req.body.meta.affix
        let alias = utils.getQueryValue(req.body.alias)===''?null:"'"+req.body.alias+"'"
        let remark = utils.getQueryValue(req.body.remark)===''?null:"'"+req.body.remark+"'"      
        let parentId = utils.getQueryValue(req.body.parentId)==''?0:req.body.parentId        
        let sort = utils.getQueryValue(req.body.sort)==''?1:req.body.sort
        let keepalive = utils.getQueryValue(req.body.meta.keepAlive)==''?0:req.body.meta.keepAlive

        let sqlStr = ''
        let newid = ''
        if (id==''){  // 新增
            if ((await mysqlHelper.query("select count(1) as ct from sys_menu where name='" + req.body.name + "'"))[0].ct > 0) {
                throw new Error('该菜单名称已被使用。')
            }
            sqlStr = "insert into sys_menu(name,parentId,title,path,component,alias,icon,type,orderInList,remark,affix,hidden,fullpage,hiddenBreadcrumb,tag,color,keepalive) values("+name+","+parentId
                    +","+title+","+path+","+component+","+alias+","+icon+","+type+","+sort+","+remark+","+affix+","+fullpage+","+hidden+","+hiddenBreadcrumb+","+tag+","+color+","+keepalive+")"
            await mysqlHelper.query(sqlStr)
            newid = (await mysqlHelper.query("select id from sys_menu where name='"+req.body.name+"'"))[0].id
        }
        else{
            sqlStr = "update sys_menu set name="+name+",title="+title +",parentId="+parentId+",orderinlist="+sort+",remark="
                    +remark+",path="+path+",fullpage="+fullpage+",hidden="+hidden+",hiddenBreadcrumb="+hiddenBreadcrumb+",icon="+icon+" "
                    + ",affix="+affix+",type="+type+",alias="+alias+",tag="+tag+",color="+color+",keepalive="+keepalive
                    + " where id="+ req.body.id
            await mysqlHelper.query(sqlStr)
            newid = req.body.id
        }
        result.code = 200       
        result.data = newid
        result.success = true
    }catch(err){
        result.code = 400
        result.success = false
        result.message = err.message
    }
    res.json(result)
})

// 删除菜单 maoyuan
router.delete('/', async function(req, res, next){
    let result = {}    
    try{
        let sqlStr = "delete from sys_menu where id in ("+req.body.ids.join()+")"
        result.code = 200       
        result.data = await mysqlHelper.query(sqlStr)
        result.success = true
    }catch(err){
        result.code = 400
        result.success = false
        result.message = err.message
    }
    res.json(result)
})

module.exports = router
